import PlayerModel from "../../model/PlayerModel";
import { Context } from "../context/Context";
import Singleton from "../context/Singleton";
import Utils from "../utils/Utils";

type TypeK = string | number | Symbol;

export default class LocalDb extends Singleton {

    private source = Laya.LocalStorage;

    private cache: any;

    public sign: any;

    onInit() {
        this.sign = Context.I.get(PlayerModel).uid;
        this.cache = Object.create(null);
    }

    setItem(key: string | number, v: any, objKey?: string) {
        key = `${this.sign || ""}_${key}`;
        if (objKey != null) {
            let oldV = this.getItem(key) || Object.create(null);
            oldV[objKey] = v;
            this.cacheItem(key, oldV);
            this.source.setJSON(key, oldV);

        } else {

            this.cacheItem(key, v);
            this.source.setItem(key, v);
        }

    }

    getItem(key: string | number, objKey?: string) {
        key = `${this.sign || ""}${key}`;

        let cache = this.cache[key];
        if (cache != null) {
            return objKey != null ? cache[objKey] : cache;
        }

        if (objKey != null) {
            let oldV = this.source.getJSON(key);
            if (!oldV) return null;
            this.cacheItem(key, oldV)
            return oldV[objKey];
        }
        let v = this.source.getItem(key);
        !Utils.isNil(v) && this.cacheItem(key, v);
        return v;
    }


    getItemAsNum(key: string | number, objKey?: string) {
        return Number(this.getItem(key, objKey));
    }


    deleteItem(key: string | number) {
        let data = this.getItem(key);
        key = `${this.sign || ""}${key}`;

        if (Utils.isNil(data)) return;

        this.cache && Reflect.deleteProperty(this.cache, key);
        this.source.removeItem(key)
    }


    //临时储存字段，重登录清空
    cacheItem(key: string, v: any) {

        if (Utils.isNil(key)) {
            return;
        }

        if (Utils.isNil(this.cache)) {
            this.cache = Object.create(null);
        }

        this.cache[key] = v;
    }

    private formtKey(k: TypeK) {
        
    }


}